package com.mercycrazy.recruit.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * JSON 通用工具类
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-15
 */
@Slf4j
public class JsonUtil {

    /**
     * 利用 response 响应 JSON 数据给前端, 基于 Jackson 实现
     *
     * @param response HttpServletResponse
     * @param obj      要响应的 JSON 数据
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {

        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(objectMapper.writeValueAsString(obj));
            response.flushBuffer();
        } catch (Exception e) {
            log.warn("响应JSON数据给前端异常", e);
        }
    }
}
